﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using RN.ERP.Web.ModelService;
using Newtonsoft.Json;
using Fly.Common.Linq;
using RN.ERP.Web.Utilities;
using System.Configuration;
using System.Web.SessionState;
using RN.ERP.Web.BasicService;


namespace RN.ERP.Web.Handlers
{
    /// <summary>
    /// AuthorityHandler 的摘要说明
    /// </summary>
    public class AuthorityHandler : IHttpHandler, IRequiresSessionState
    {
        private AuthorityService.AuthorityServiceClient client = new AuthorityService.AuthorityServiceClient();
        private EnterpriseService.EnterpriseServiceClient enterClient = new EnterpriseService.EnterpriseServiceClient();
        private OrderService.OrderServiceClient orderClient = new OrderService.OrderServiceClient();
        string corpName = string.Empty;
        string corpUserGuid = string.Empty;
        string isrtUserGuid = string.Empty;
        string type = string.Empty;
        string appid = ConfigurationManager.AppSettings["AppId"];

        public void ProcessRequest(HttpContext context)
        {
            corpName = context.Request.QueryString["corpName"];
            corpUserGuid = context.Request.QueryString["corpUserGuid"];
            isrtUserGuid = context.Request["IsrtUserGuid"];
            type = context.Request["type"];

            string corpInfo = context.Request["CorpInfo"];
            string sysInfo = context.Request["SysInfo"];

            string action = context.Request.QueryString["act"];
            if (!string.IsNullOrEmpty(action))
            {
                switch (action.ToLower())
                {
                    case "getroles":
                        UtilitiesTool.OutputData(GetRoles(context), string.Empty);
                        break;
                    case "getperusers":
                        UtilitiesTool.OutputData(GetPerUsers(context), string.Empty);
                        break;
                    case "getfunc":
                        UtilitiesTool.OutputData(GetFuncs(context), string.Empty);
                        break;
                    case "getfuncforuser":
                        UtilitiesTool.OutputData(GetFuncsForUser(context), string.Empty);
                        break;
                    case "getusers":
                        UtilitiesTool.OutputData(GetUsersInfo(context), string.Empty);
                        break;
                    case "getsys":
                        UtilitiesTool.OutputData(GetSysApp(context, corpUserGuid), string.Empty);
                        break;
                    case "dosaveuser":
                        UtilitiesTool.OutputData(SaveUserSys(context, corpInfo, sysInfo), string.Empty);
                        break;
                    case "dosaverolebyre":
                        UtilitiesTool.OutputData(SaveRoleByRe(context), string.Empty);
                        break;
                    case "getcainfo":
                        UtilitiesTool.OutputData(GetCAInfo(context, corpUserGuid), string.Empty);
                        break;
                    case "saveper":
                        UtilitiesTool.OutputData(SavePermission(context), string.Empty);
                        break;
                    case "addrole":
                        UtilitiesTool.OutputData(AddOrEditRole(context), string.Empty);
                        break;
                    case "addmapping":
                        UtilitiesTool.OutputData(AddMapping(context), string.Empty);
                        break;
                    case "deleterole":
                        UtilitiesTool.OutputData(DeleteRole(context), string.Empty);
                        break;
                    case "getmenu":
                        UtilitiesTool.OutputData(GetMenu(context), string.Empty);
                        break;
                    case "addfunc":
                        UtilitiesTool.OutputData(AddOrEditFunc(context), string.Empty);
                        break;
                    case "deletefunc":
                        UtilitiesTool.OutputData(DeleteFunc(context), string.Empty);
                        break;
                    case "getdepartment":
                        UtilitiesTool.OutputData(GetDepartment(context), string.Empty);
                        break;
                    case "adddepartment":
                        UtilitiesTool.OutputData(AddDepartment(context), string.Empty);
                        break;
                    case "deletedepartment":
                        UtilitiesTool.OutputData(DeleteDepartment(context), string.Empty);
                        break;
                    default:
                        break;
                }
            }

        }

        //单个用户获取权限信息
        private string GetFuncsForUser(HttpContext context)
        {
            RN.ERP.Web.AuthorityService.FuncQueryCondition condition = new RN.ERP.Web.AuthorityService.FuncQueryCondition()
            {
                IsDel = false
            };
            condition.AppID = appid;

            string strFuncs = client.GetFunctionList(condition);//获取功能总列表
            string strRolePerm = string.Empty;
            string strUserPerm = string.Empty;
            string strPerm = string.Empty;

            if (!string.IsNullOrEmpty(context.Request.QueryString["userID"]))
            {
                strPerm = client.GetFuncPermissionForUser(Guid.Empty, Guid.Parse(context.Request.QueryString["userID"]), appid);
            }

            //List<AuthorityService.T_Sys_FuncPermission> permission = null;
            //if (!string.IsNullOrEmpty(strPerm)) 
            //{
            //    permission = JsonConvert.DeserializeObject<List<AuthorityService.T_Sys_FuncPermission>>(strPerm);
            //}

            return CreateFuncs(strFuncs, strPerm);
        }

        private string GetFuncs(HttpContext context)
        {
            RN.ERP.Web.AuthorityService.FuncQueryCondition condition = new RN.ERP.Web.AuthorityService.FuncQueryCondition()
            {
                IsDel = false
            };
            condition.AppID = appid;
            if (!string.IsNullOrEmpty(context.Request.QueryString["parent"]))
            {
                condition.ParentGuid = Guid.Parse(context.Request.QueryString["parent"]);
                string strFuncs = client.GetFunctionList(condition);//获取子功能列表
                return strFuncs;
            }
            else
            {
                string strFuncs = client.GetFunctionList(condition);//获取功能总列表
                string strPerm = string.Empty;
                if (!string.IsNullOrEmpty(context.Request.QueryString["roleID"]))
                {
                    strPerm = client.GetFuncPermission(Guid.Parse(context.Request.QueryString["roleID"]), appid);//获取某个角色的权限
                }
                else if (!string.IsNullOrEmpty(context.Request.QueryString["userID"]))
                {
                    strPerm = client.GetUserMenus(context.Request.QueryString["userID"].ToString(), null, appid);//获取某个用户的权限
                }
                return CreateFuncs(strFuncs, strPerm);
            }
        }

        private string CreateFuncs(string strFuncs, string strPerm)
        {
            var data = new List<Dictionary<string, object>>();
            var functions = JsonConvert.DeserializeObject<IList<T_Sys_Function>>(strFuncs);
            List<AuthorityService.T_Sys_FuncPermission> permission = null;
            if (!string.IsNullOrEmpty(strPerm))//如果接收到角色或用户guid则标记已有功能
            {
                permission = JsonConvert.DeserializeObject<List<AuthorityService.T_Sys_FuncPermission>>(strPerm);
            }

            ////获取一级功能
            var function1 = functions.Where(f => f.ParenGuid == Guid.Empty).ToList();
            foreach (T_Sys_Function function in function1)
            {
                var dic = ConvertFuncs(function);
                if (permission != null)
                {
                    Guid funcguid = Guid.Parse(dic["MenuID"].ToString());
                    if (permission.Where(p => p.FunctionGuid == funcguid).Count() > 0)
                    {
                        dic["Permit"] = true;
                    }
                }
                var function2 = functions.Where(f => f.ParenGuid == function.FunctionGuid).ToList();
                if (function2 != null && function2.Count > 0)
                {
                    var dicChildren = new List<Dictionary<string, object>>();
                    foreach (T_Sys_Function functionSub in function2)
                    {
                        var dicSubMenu = ConvertFuncs(functionSub);
                        if (permission != null)
                        {
                            Guid func = Guid.Parse(dicSubMenu["MenuID"].ToString());
                            if (permission.Where(p => p.FunctionGuid == func).Count() > 0)
                            {
                                dicSubMenu["Permit"] = true;
                            }
                        }
                        dicChildren.Add(dicSubMenu);
                    }
                    dic["children"] = dicChildren;
                }
                data.Add(dic);
            }
            return JsonConvert.SerializeObject(data);
        }

        private Dictionary<string, object> ConvertFuncs(T_Sys_Function entity)
        {
            return new Dictionary<string, object>()
            {
                {"Permit",false},
                {"AccessName",entity.Title},
                {"AccessUrl",entity.Url},
                {"AccessNo",entity.Code}, 
                {"MenuID",entity.FunctionGuid},
                {"AccessAppID",entity.AppID},
                {"SortIndex",entity.SortIndex},
                {"BtnID",0},
                {"DESCRIPTION",entity.DESCRIPTION}
            };
        }

        private string GetRoles(HttpContext context)
        {
            string strRoles = client.GetRoles(string.Empty, string.Empty, string.Empty, string.Empty);
            IList<T_Sys_Roles> roles = JsonConvert.DeserializeObject<IList<T_Sys_Roles>>(strRoles);
            var result = roles.Select(r => new Role() { Id = r.RoleGuid.ToString(), AreaCode = r.AreaCode, Code = r.Code, Description = r.Description, Title = r.Title, Group = r.GroupId.ToString() });
            return JsonConvert.SerializeObject(result);
            //@"{""Rows"":" + JsonConvert.SerializeObject(result) + @",""Total"":""" + roles.Count + @"""}";
        }

        private string GetPerUsers(HttpContext context)
        {
            string name = context.Request.QueryString["name"];
            string username = context.Request.QueryString["username"];
            string strRoles = client.GetUserList(name, username);
            IList<T_Sys_Users> roles = JsonConvert.DeserializeObject<IList<T_Sys_Users>>(strRoles);
            var result = roles.Select(r => new User()
            {
                CorpUserGuid = r.UserGuid.ToString(),
                CorpName = r.Name,
                UserName = r.UserName,
                RoleID = r.RoleID,
                AreaCode = r.AreaCode
            });
            string res = JsonConvert.SerializeObject(result);
            return res;
        }

        private string SavePermissionForUser(HttpContext context)
        {
            SessionUserInfo user = (SessionUserInfo)HttpContext.Current.Session[SessionConstant.SESSION_USERINFO];
            string[] strs = null;
            if (!string.IsNullOrEmpty(context.Request.Params["guids"]))//要保存的功能guid集合
            {
                strs = context.Request.Params["guids"].Split(new string[] { "@" }, StringSplitOptions.RemoveEmptyEntries);
            }

            if (!string.IsNullOrEmpty(context.Request.QueryString["selectedID"]) && strs != null)
            {
                try
                {
                    Guid selectedID = Guid.Parse(context.Request.QueryString["selectedID"].ToString());//人的guid
                    client.SaveorUpdateFuncPermissionForUser(Guid.Empty, selectedID, appid, strs);

                    return JsonConvert.SerializeObject(new { Message = "保存成功" });
                }
                catch (Exception)
                {
                }
            }
            return JsonConvert.SerializeObject(new { Message = "操作失败" });
        }

        private string SavePermission(HttpContext context)
        {
            if (type.Equals("1"))
            {
                return SavePermissionForUser(context);
            }
            SessionUserInfo user = (SessionUserInfo)HttpContext.Current.Session[SessionConstant.SESSION_USERINFO];
            string[] strs = null;
            if (!string.IsNullOrEmpty(context.Request.Params["guids"]))//要保存的功能guid集合
            {
                strs = context.Request.Params["guids"].Split(new string[] { "@" }, StringSplitOptions.RemoveEmptyEntries);
            }

            List<AuthorityService.T_Sys_FuncPermission> strPerm = null;
            if (!string.IsNullOrEmpty(context.Request.QueryString["selectedID"]) && strs != null)
            {
                try
                {
                    Guid selectedID = Guid.Parse(context.Request.QueryString["selectedID"].ToString());
                    strPerm = JsonConvert.DeserializeObject<List<AuthorityService.T_Sys_FuncPermission>>(client.GetFuncPermission(selectedID, appid));//原有功能
                    for (int i = 0; i < strs.Length; i++)//先将新集合一一与原有数据比较，如果不存在则新增或修改原删除数据
                    {
                        Guid funguid = Guid.Parse(strs[i]);
                        if (strPerm.Where(f => f.FunctionGuid == funguid && f.ObjectGuid == selectedID && f.IsDel == false).Count() > 0)
                        {
                            continue;
                        }
                        else
                        {
                            AuthorityService.T_Sys_FuncPermission perm = new AuthorityService.T_Sys_FuncPermission();
                            perm.FunctionGuid = funguid;
                            perm.ObjectGuid = selectedID;
                            perm.FuncType = 0;
                            perm.Type = int.Parse(context.Request.QueryString["type"].ToString());
                            perm.IsDel = false;
                            perm.IsrtUseID = user != null ? Guid.Parse(user.CorpUserGuid) : Guid.Empty;
                            perm.IsrtDate = DateTime.Now;
                            client.AddFuncPermission(perm);
                        }
                    }
                    foreach (var funcper in strPerm)//再讲原有数据一一与新数据比较，不存在则删除
                    {
                        string funcguid = funcper.FunctionGuid.ToString();
                        if (!strs.Contains(funcguid))
                        {
                            client.DelFuncPermission(funcper.FunctionGuid, selectedID);
                        }
                    }
                    return JsonConvert.SerializeObject(new { Message = "保存成功" });
                }
                catch (Exception)
                {
                }
            }
            return JsonConvert.SerializeObject(new { Message = "操作失败" });
        }

        private string AddOrEditRole(HttpContext context)
        {
            SessionUserInfo user = (SessionUserInfo)HttpContext.Current.Session[SessionConstant.SESSION_USERINFO];
            string data = context.Request.QueryString["data"];
            //string Title = context.Request.Params["Title"];
            if (!string.IsNullOrEmpty(data))
            {
                Role role = JsonConvert.DeserializeObject<Role>(data);
                int group = 1;
                int.TryParse(role.Group, out group);
                if (group != 2) group = 1;
                if (!string.IsNullOrEmpty(role.Id))//修改
                {
                    AuthorityService.T_Sys_Roles uproles = new AuthorityService.T_Sys_Roles();
                    uproles.RoleGuid = Guid.Parse(role.Id);
                    uproles.Title = role.Title;
                    uproles.Description = role.Description;
                    uproles.Code = role.Code;
                    uproles.AreaCode = role.AreaCode;
                    uproles.IsrtUseID = user != null ? Guid.Parse(user.CorpUserGuid) : Guid.Empty;
                    uproles.GroupId = group;
                    uproles.IsDel = false;
                    OperationResult result = JsonConvert.DeserializeObject<OperationResult>(client.UpdateRole(uproles));
                    return JsonConvert.SerializeObject(new { Message = result.Message });
                }
                else //添加
                {
                    AuthorityService.T_Sys_Roles uproles = new AuthorityService.T_Sys_Roles();
                    uproles.RoleGuid = Guid.NewGuid();
                    uproles.Title = role.Title;
                    uproles.Description = role.Description;
                    uproles.Code = role.Code;
                    uproles.AreaCode = role.AreaCode;
                    uproles.IsrtUseID = user != null ? Guid.Parse(user.CorpUserGuid) : Guid.Empty;
                    uproles.IsrtDate = DateTime.Now;
                    uproles.GroupId = group;
                    uproles.IsDel = false;
                    OperationResult result = JsonConvert.DeserializeObject<OperationResult>(client.AddRole(uproles));
                    return JsonConvert.SerializeObject(new { Message = result.Message });
                }
            }
            return JsonConvert.SerializeObject(new { Message = "操作失败" });
        }

        private string AddMapping(HttpContext context)
        {
            OperationResult result = new OperationResult();
            string code = context.Request.QueryString["funccode"];
            string funcurl = context.Request.QueryString["funcurl"];
            if (funcurl.Trim().Contains("http"))
            {
                result.Message = "该功能无需映射！";
            }
            else
            {
                AuthorityService.FuncPageMapping mapping = new AuthorityService.FuncPageMapping();
                mapping.KeyGuid = Guid.NewGuid();
                mapping.AppId = appid;
                mapping.PageCode = funcurl.Split('?')[0].Replace('/', '_').Replace('.', '_');
                mapping.FuncCode = code;
                result = JsonConvert.DeserializeObject<OperationResult>(client.AddPageMapping(mapping));
                if (result.Result)
                {
                    ////添加完以后重新加载功能页面映射关系
                    BasicServiceClient baseeClient = new BasicServiceClient();
                    var funcPageMapping = JsonConvert.DeserializeObject<List<ModelService.T_Sys_FuncPageMapping>>(baseeClient.GetFuncPageMapping(appid));
                    HttpContext.Current.Application.Remove(ApplicationConstant.APPLICATION_FUNCPAGEMAPPING);
                    HttpContext.Current.Application[ApplicationConstant.APPLICATION_FUNCPAGEMAPPING] = funcPageMapping;
                }
            }
            return JsonConvert.SerializeObject(new { Message = result.Message });
        }

        private string DeleteRole(HttpContext context)
        {
            string roleid = context.Request.QueryString["roleid"];
            if (!string.IsNullOrEmpty(roleid))
            {
                OperationResult result = JsonConvert.DeserializeObject<OperationResult>(client.DeleteRole(roleid));
                return JsonConvert.SerializeObject(new { Message = result.Message });
            }
            return JsonConvert.SerializeObject(new { Message = "操作失败" });
        }

        private string AddOrEditFunc(HttpContext context)
        {
            SessionUserInfo user = (SessionUserInfo)HttpContext.Current.Session[SessionConstant.SESSION_USERINFO];
            string Title = context.Request.Params["Title"];
            string Code = context.Request.Params["Code"];
            string Url = context.Request.QueryString["funcurl"];
            string DESCRIPTION = context.Request.Params["DESCRIPTION"];
            string FunctionGuid = context.Request.Params["FunctionGuid"];
            string ParenGuid = context.Request.Params["ParenGuid"];
            Guid pguid = Guid.Empty;
            Guid.TryParse(ParenGuid, out pguid);
            if (!string.IsNullOrEmpty(Title))
            {
                if (!string.IsNullOrEmpty(FunctionGuid))//修改
                {
                    AuthorityService.T_Sys_Function func = new AuthorityService.T_Sys_Function();
                    func.FunctionGuid = Guid.Parse(FunctionGuid);
                    func.Code = Code;
                    func.Title = Title;
                    func.DESCRIPTION = DESCRIPTION;
                    //func.ParenGuid = pguid;
                    //func.RootGuid = Guid.Empty;
                    func.Url = pguid == Guid.Empty ? "#" : Url;
                    //func.IsMenu = true;
                    //func.AppID = appid;
                    func.IsrtUseID = user != null ? Guid.Parse(user.CorpUserGuid) : Guid.Empty;
                    func.IsrtDate = DateTime.Now;
                    func.IsDel = false;
                    OperationResult result = JsonConvert.DeserializeObject<OperationResult>(client.UpdateFunction(func));
                    return JsonConvert.SerializeObject(new { Message = result.Message });
                }
                else
                {
                    AuthorityService.T_Sys_Function func = new AuthorityService.T_Sys_Function();
                    func.FunctionGuid = Guid.NewGuid();
                    func.Code = Code;
                    func.Title = Title;
                    func.DESCRIPTION = DESCRIPTION;
                    func.ParenGuid = pguid;
                    func.RootGuid = Guid.Empty;
                    func.Url = pguid == Guid.Empty ? "#" : Url;
                    func.IsMenu = true;
                    func.AppID = appid;
                    func.IsrtUseID = user != null ? Guid.Parse(user.CorpUserGuid) : Guid.Empty;
                    func.IsrtDate = DateTime.Now;
                    func.IsDel = false;
                    OperationResult result = JsonConvert.DeserializeObject<OperationResult>(client.AddFunction(func));
                    return JsonConvert.SerializeObject(new { Message = result.Message });
                }
            }
            return JsonConvert.SerializeObject(new { Message = "操作失败" });
        }

        private string DeleteFunc(HttpContext context)
        {
            string funcid = context.Request.QueryString["funcid"];
            if (!string.IsNullOrEmpty(funcid))
            {
                OperationResult result = JsonConvert.DeserializeObject<OperationResult>(client.DeleteFunction(Guid.Parse(funcid)));
                return JsonConvert.SerializeObject(new { Message = result.Message });
            }
            return JsonConvert.SerializeObject(new { Message = "操作失败" });
        }

        private string GetMenu(HttpContext context)
        {
            RN.ERP.Web.AuthorityService.FuncQueryCondition condition = new RN.ERP.Web.AuthorityService.FuncQueryCondition()
            {
                IsDel = false
            };
            condition.AppID = appid;
            condition.ParentGuid = Guid.Empty;
            string strFuncs = client.GetFunctionList(condition);
            return CreateParFuncs(strFuncs);
        }

        private string CreateParFuncs(string strFuncs)
        {
            var data = new Dictionary<string, object>()
            {
                {"text","主菜单"},
                {"icon","../images/category.gif"}
            };
            var dicChildren = new List<Dictionary<string, object>>();
            var functions = JsonConvert.DeserializeObject<IList<T_Sys_Function>>(strFuncs);
            foreach (T_Sys_Function function in functions)
            {
                var dic = new Dictionary<string, object>()
            {
                {"MenuParentNo",null},
                {"MenuNo",function.Code},
                {"id",function.FunctionGuid},
                {"text",function.Title+"("+function.Code+")"},
                {"icon","../images/application.png"}
            };
                dicChildren.Add(dic);
            }
            data["children"] = dicChildren;
            var json = "[" + JsonConvert.SerializeObject(data) + "]";
            return json;
        }

        #region 获取用户信息
        private string GetUsersInfo(HttpContext context)
        {
            var queryCondition = GetCondition();
            var strCorps = enterClient.GetCompaniesInfo(queryCondition, "");
            IList<CompanyInfo> corps = JsonConvert.DeserializeObject<IList<CompanyInfo>>(strCorps);
            var result = corps.Select(r => new User()
            {
                CorpUserGuid = r.CorpUserGuid.ToString(),
                CorpName = r.CorpName,
                AreaCode = r.AreaCode.ToString(),
                Address = r.Address,
                Type = r.Type,
                LinkMan1 = r.LinkMan1,
                QualificationLevel = r.QualificationLevel,
                BussinessArea = r.BussinessArea
            });
            return JsonConvert.SerializeObject(result);
        }

        private string GetCondition()
        {
            List<QueryCompanyInfoCondition> queryCompanyInfoList = new List<QueryCompanyInfoCondition>();
            QueryCompanyInfoCondition queryCompanyInfoCondition = new QueryCompanyInfoCondition();

            if (!string.IsNullOrEmpty(corpName))
            {
                queryCompanyInfoCondition.CorpName = new ParameterValue<string>() { O = OptEnum.Like, V = corpName };
            }
            //else
            //{
            //    queryCompanyInfoCondition.AreaCode = new ParameterValue<string>() { O = OptEnum.Like, V = "02" };
            //}
            queryCompanyInfoList.Add(queryCompanyInfoCondition);

            return JsonConvert.SerializeObject(queryCompanyInfoList);
        }
        #endregion

        #region 获取系统信息
        private string GetSysApp(HttpContext context, string corpUserGuid)
        {
            if (string.IsNullOrEmpty(corpUserGuid))
            {
                return null;
            }

            string strSys = client.GetSysApp();
            IList<T_Sys_Application> apps = JsonConvert.DeserializeObject<IList<T_Sys_Application>>(strSys);

            string strPer = client.GetUserSysPermission(corpUserGuid, 2);
            IList<AuthorityService.T_Sys_FuncPermission> pers = JsonConvert.DeserializeObject<IList<AuthorityService.T_Sys_FuncPermission>>(strPer);
            var resultPer = apps.GroupJoin(pers, a => a.KeyGuid, p => p.FunctionGuid,
                (a, p) => new { KeyGuid = a.KeyGuid.ToString(), AppId = a.AppId, Title = a.Title, IsDel = string.Join(",", p.Select(x => x.IsDel.ToString()).ToArray()) });
            return JsonConvert.SerializeObject(resultPer);
        }

        /// <summary>
        /// 获取用户已有系统权限，包含已删除 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="corpUserGuid"></param>
        /// <returns></returns>
        private List<AuthorityService.T_Sys_FuncPermission> GetUserSysList(string corpUserGuid)
        {
            List<AuthorityService.T_Sys_FuncPermission> list = null;
            if (!string.IsNullOrEmpty(corpUserGuid))
            {
                string strPer = client.GetUserSysPermission(corpUserGuid, 2);
                list = JsonConvert.DeserializeObject<List<AuthorityService.T_Sys_FuncPermission>>(strPer);
            }
            return list;
        }


        #endregion

        /// <summary>
        /// 获取CA信息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="corpUserGuid"></param>
        /// <returns></returns>
        private string GetCAInfo(HttpContext context, string corpUserGuid)
        {
            string strCA = orderClient.GetCAInfo(corpUserGuid);
            List<CAPayinfo_Productinfo> cas = JsonConvert.DeserializeObject<List<CAPayinfo_Productinfo>>(strCA);
            var result = cas.Select(r => r);

            return JsonConvert.SerializeObject(result);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="context"></param>
        /// <param name="corpUserGuid"></param>
        /// <param name="selectSys"></param>
        /// <returns></returns>
        private string SaveUserSys(HttpContext context, string corpUserGuid, string selectSys)
        {
            List<AuthorityService.T_Sys_FuncPermission> new_list = new List<AuthorityService.T_Sys_FuncPermission>();
            List<string> new_list2 = new List<string>();

            if (!string.IsNullOrEmpty(selectSys))
            {
                new_list2 = selectSys.Split(',').ToList();
            }

            Guid? IsrtUserGuid = null;
            if (!string.IsNullOrEmpty(isrtUserGuid))
            {
                IsrtUserGuid = new Guid(isrtUserGuid);
            }

            List<AuthorityService.T_Sys_FuncPermission> old_list = this.GetUserSysList(corpUserGuid);
            old_list = old_list.Where(r => r.IsDel == false).ToList();
            List<string> old_list2 = new List<string>();
            old_list2 = old_list.Select(r => r.FunctionGuid.ToString()).ToList();

            List<string> listDel_str = old_list2.Except(new_list2).ToList();
            List<string> listAdd_str = new_list2.Except(old_list2).ToList();

            AuthorityService.T_Sys_FuncPermission en = null;
            foreach (string str in listAdd_str)
            {
                en = new AuthorityService.T_Sys_FuncPermission()
                 {
                     ObjectGuid = new Guid(corpUserGuid),
                     IsDel = false,
                     FunctionGuid = new Guid(str),
                     FuncType = 0,
                     IsrtDate = DateTime.Now,
                     Type = 2,
                     IsrtUseID = IsrtUserGuid
                 };
                client.AddFuncPermission(en);
            }

            foreach (string str in listDel_str)
            {
                en = new AuthorityService.T_Sys_FuncPermission()
                {
                    ObjectGuid = new Guid(corpUserGuid),
                    IsDel = true,
                    FunctionGuid = new Guid(str),
                    FuncType = 0,
                    IsrtDate = DateTime.Now,
                    Type = 2,
                    IsrtUseID = IsrtUserGuid
                };
                client.UpdatePermission(en);
            }
            return "设置成功！";
        }

        private string SaveRoleByRe(HttpContext context)
        {
            string rst = string.Empty;
            string userGuid = context.Request["UserGuid"];
            string txtRoleNum = context.Request["RoleNum"];
            string txtRoleArea = context.Request["RoleArea"];

            OperationResult result = JsonConvert.DeserializeObject<OperationResult>(client.SetUserRole(new Guid(userGuid), txtRoleNum, txtRoleArea));
            rst = result.Message;

            return rst;
        }

        private string GetUsers(HttpContext context)
        {
            return null;
        }

        private string GetRolePermission(HttpContext context)
        {
            string roleGuid = context.Request.QueryString["role"];
            string appId = appid;
            client.GetRoleFunctions(roleGuid, string.Empty, appId);
            return null;
        }

        /// <summary>
        /// 获取部门信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string GetDepartment(HttpContext context)
        {
            string sysArea = ConfigurationManager.AppSettings["sysArea"];
            string depStr = client.GetDepartmentData(sysArea);
            return depStr;
        }

        /// <summary>
        /// 新增或修改部门信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string AddDepartment(HttpContext context)
        {
            string data = context.Request.QueryString["data"];
            string sysArea = ConfigurationManager.AppSettings["sysArea"];
            
            if (!string.IsNullOrEmpty(data))
            {
                Dept dept = JsonConvert.DeserializeObject<Dept>(data);
                AuthorityService.dict_Department department = new AuthorityService.dict_Department();
                department.DeptID = string.IsNullOrEmpty(dept.DeptID) ? 0 : Convert.ToInt32(dept.DeptID);
                department.DepartName = dept.DepartName;
                department.AreaCode = dept.AreaCode;
                department.OrderNum = string.IsNullOrEmpty(dept.OrderNum) ? 0 : Convert.ToInt32(dept.OrderNum);
                department.isStatistic = dept.isStatistic == "1" ? true : false;

                if (!string.IsNullOrEmpty(dept.ID))////修改
                {
                    department.ID = Convert.ToInt32(dept.ID);

                    OperationResult result = JsonConvert.DeserializeObject<OperationResult>(client.UpdateDepartment(department));
                    return JsonConvert.SerializeObject(new { Message = result.Message });
                }
                else ////添加
                {
                    department.SysAreaCode = sysArea;

                    OperationResult result = JsonConvert.DeserializeObject<OperationResult>(client.AddDepartment(department));
                    return JsonConvert.SerializeObject(new { Message = result.Message });
                }
            }
            return JsonConvert.SerializeObject(new { Message = "操作失败" });
        }

        /// <summary>
        /// 删除部门信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string DeleteDepartment(HttpContext context)
        {
            int deptid = 0;
            string deptidStr = context.Request.QueryString["deptid"];
            if (!string.IsNullOrEmpty(deptidStr))
            {
                int.TryParse(deptidStr, out deptid);
                OperationResult result = JsonConvert.DeserializeObject<OperationResult>(client.DeleteDepartment(deptid));
                return JsonConvert.SerializeObject(new { Message = result.Message });
            }
            return JsonConvert.SerializeObject(new { Message = "操作失败" });
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #region 返回实体

        private class Role
        {
            public string Id { get; set; }
            public string Title { get; set; }
            public string Code { get; set; }
            public string AreaCode { get; set; }
            public string Description { get; set; }
            public string Group { get; set; }
        }

        private class User
        {
            public string CorpUserGuid { get; set; }
            public string CorpName { get; set; }
            public string AreaCode { get; set; }
            public string Address { get; set; }
            public string Type { get; set; }
            public string LinkMan1 { get; set; }
            public string QualificationLevel { get; set; }
            public string BussinessArea { get; set; }
            public string UserName { get; set; }
            public int? RoleID { get; set; }
        }

        private class Dept
        {
            public string ID { get; set; }
            public string DeptID { get; set; }
            public string DepartName { get; set; }
            public string AreaCode { get; set; }
            public string OrderNum { get; set; }
            public string isStatistic { get; set; }
        }

        #endregion

        #region Del
        private class T_Sys_Application
        {
            public Int32 Id { get; set; }
            public Guid KeyGuid { get; set; }
            public Int32 AppId { get; set; }
            public String Title { get; set; }
            public String SettingContent { get; set; }
            public String Description { get; set; }
            public Boolean? IsDel { get; set; }
        }


        private class CAPayinfo_Productinfo
        {
            public String iTitle { get; set; }
            public String AreaCode { get; set; }
            public String LinkPerson { get; set; }
            public String SendAddress { get; set; }
            public String officeTel { get; set; }
            public String mobileTel { get; set; }
            public Byte bCAStatus { get; set; }
            public Double? SumPay { get; set; }
            public String FlowCode { get; set; }
            public DateTime? RegisterDate { get; set; }

            public String CAStatus { get; set; }

            public String bCAKind { get; set; }
            public Int32? SourceID { get; set; }

            public String Title { get; set; }
            public String Description { get; set; }
        }

        #endregion

    }
}